A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
fruits = {"apple", "banana", "cherry"}
print(fruits)
for x in thisset:
print(x)
Check if "banana" is present in the set:
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
fruits = {"apple", "banana", "cherry"}
fruits.add{"orange"}
print(fruits)
fruits.update(["orange", "mango", "grapes"])
print(fruits)
Get the Length of a Set
To determine how many items a set has, use the len() method.
fruits = {"apple", "banana", "cherry"}
print(len(fruits))
Remove Items
To remove an item in a set, use the remove(), or the discard() method.
Remove "banana" by using the remove() method:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
Remove "banana" by using the discard() method:
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
print(fruits)
for x in thisset:
print(x)
Check if "banana" is present in the set:
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
fruits = {"apple", "banana", "cherry"}
fruits.add{"orange"}
print(fruits)
fruits.update(["orange", "mango", "grapes"])
print(fruits)
Get the Length of a Set
To determine how many items a set has, use the len() method.
fruits = {"apple", "banana", "cherry"}
print(len(fruits))
Remove Items
To remove an item in a set, use the remove(), or the discard() method.
Remove "banana" by using the remove() method:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
Remove "banana" by using the discard() method:
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
No comments:
Post a Comment